package com.vigor.bear.webapp.contoller;

import java.util.List;

import com.vigor.bear.mybatis.Pagination;
import com.vigor.bear.webapp.bean.Json;
import com.vigor.bear.webapp.bean.Message;
import com.vigor.bear.webapp.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService msg;

    @RequestMapping("post")
    @ResponseBody
    public Json post(@ModelAttribute Message message) {
        Json json = new Json();
        int ret = msg.post(message);
        json.setSuccess(ret > 0);
        return json;
    }

    @RequestMapping(value = "/delete/{mid}", method = RequestMethod.POST)
    @ResponseBody
    public Json delete(@PathVariable("mid") int mid) {
        Json json = new Json();
        int ret = msg.delete(mid);
        json.setSuccess(ret > 0);
        return json;
    }

    @RequestMapping("/view/{mid}")
    public ModelAndView view(ModelAndView model, @PathVariable("mid") int mid) {
        Message message = msg.view(mid);
        model.addObject("message", message);
        model.setViewName("view");
        return model;
    }

    @RequestMapping("/list/{offset}-{limit}")
    public ModelAndView list(ModelAndView model, @PathVariable("offset") int offset, @PathVariable("limit") int limit) {
        Pagination pagination = new Pagination(offset, limit);
        List<Message> messages = msg.list(pagination);
        model.setViewName("list");
        model.addObject("pagination", pagination);
        model.addObject("messages", messages);
        return model;
    }
}
